from jzdform import xlsx2docx1
from landform import xlsx2docx2
from docx import Document
from docxcompose.composer import Composer

from decimal import Decimal
from random import choice
from docx import Document
from docx.enum.style import WD_STYLE_TYPE
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
from docx.shared import Cm
from openpyxl import load_workbook
from docx.shared import Pt
from docx.oxml.ns import qn
from docx.shared import Cm, Inches, Pt # 导入单位换算函数
from docx.enum.section import WD_ORIENTATION
import re

import pythoncom
import win32com
import win32com.client

#获取word文档页数
def get_word_page(word_path):
    pythoncom.CoInitialize()
    # 调用word程序，不在前台显示
    w = win32com.client.Dispatch("Word.Application")
    w.Visible = 0
    w.DisplayAlerts = 0
    # 打开一个word文档
    doc = w.Documents.Open(r'C:\Users\LXL\PycharmProjects\Aoanreport\\'+word_path)
    # 获取总页数
    w.ActiveDocument.Repaginate()
    pages = w.ActiveDocument.ComputeStatistics(2)
    print(pages)
    # 保存并关闭
    doc.SaveAs(r'C:\Users\LXL\PycharmProjects\Aoanreport\\'+word_path)
    doc.Close()
    return pages
def main(files,final_docx):
    new_document = Document()
    composer = Composer(new_document)

    # report1 = Document(files[0])
    # composer = Composer(report1)
    # report2 = Document(files[1])
    # composer.append(report2)
    # section = report2.sections[0]
    #
    # section.page_width = Cm(21)  # 设置A4纸的宽度
    # section.page_height = Cm(29.7)  # 设置A4纸的高度
    #
    # section.orientation = WD_ORIENTATION.LANDSCAPE
    # new_width, new_height = section.page_height, section.page_width
    # section.page_width = new_width
    # section.page_height = new_height

    # composer.save(final_docx)

    for fn in files:
        composer.append(Document(fn))
        section = new_document.sections[-1]
        section.start_type
        # section = new_document.add_section(WD_SECTION.ODD_PAGE)
        # section.start_type
        section.page_width = Cm(21)  # 设置A4纸的宽度
        section.page_height = Cm(29.7)  # 设置A4纸的高度

        section.orientation = WD_ORIENTATION.LANDSCAPE
        new_width, new_height = section.page_height, section.page_width
        section.page_width = new_width
        section.page_height = new_height
    composer.save(final_docx)

get_word_page("report1.docx")
main(["report1.docx","report2.docx"],"result.docx")


def landform_basics(self):
    list = []  # 存储数据表QSDWMC中去重后的名称
    self.sarea = []  # 存储数据表Shape_Area数值
    self.dlmc = []  # 存储数据表DLMC名称
    self.qsdwmc = []  # 存储数据表QSDWMC中未去重的名称

    self.land = ['水田', '水浇地', '旱地', '果园', '有林地', '沟渠',
                 '道路', '坑塘水面', '设施农用地', '田坎', '仓储用地',
                 '科教用地', '城市', '建制镇', '村庄', '公路', '水利设施用地',
                 '墓葬地', '其他草地']
    self.types = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21]  # 需要输入数据的序列

    self.types2 = ['B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
                   'U']  # 需要输入数据的序列

    # def get_variable_name(variable):
    #     callers_local_vars = inspect.currentframe().f_back.f_locals.items()
    #     return [var_name for var_name, var_val in callers_local_vars if var_val is variable]

    # 读取数据表中的数据


def readexcel(self):
    file = 'qqq11.xls'

    # 创建工作空间
    workbook = xlrd.open_workbook(file)
    # 选取第0个表
    self.sheet1 = workbook.sheet_by_index(0)

    # 获取第4列数据
    self.dlmclist = (self.sheet1.col_values(4))
    # 把第一行标题弹出去
    self.dlmclist.pop(0)

    # 获取第13列数据
    self.sarealist = (self.sheet1.col_values((13)))
    self.sarealist.pop(0)

    n1 = len(self.sarealist)
    # 数据添加到列表
    for a in range(0, n1):
        self.sarea.append(self.sarealist[a])

    n2 = len(self.dlmclist)
    for b in range(0, n2):
        self.dlmc.append(self.dlmclist[b])

    # dlmclist.append(sheet1.col_values(4))
    # 获取第5列数据
    iplist = (self.sheet1.col_values(5))
    iplist.pop(0)  # 把第一行标题弹出去
    for i in iplist:
        if i not in list:  # 去掉重复的
            list.append(i)
    # print(sheet1.cell_value(row,5))
    # n3 = len(iplist)
    for b in range(0, n2):  # 将有未去重的数据添加到列表
        self.qsdwmc.append(self.iplist[b])


# 在模板中写入数据
def writeexcel(self):
    file = '土地分类面积表2.xlsx'

    workbook = openpyxl.load_workbook(file)  # 创建工作空间
    self.sheet1 = workbook['Sheet1']  # 选取Sheet1表

    # 边框设置
    self.border_set = Border(left=Side(style='medium', color=colors.BLACK),
                             right=Side(style='medium', color=colors.BLACK),
                             top=Side(style='medium', color=colors.BLACK),
                             bottom=Side(style='medium', color=colors.BLACK))
    # sheet1['B12'].border = border_set
    # workbook.save('test1.xlsx')
    self.font1 = Font(name=u'Calibri', bold=False, italic=False, size=10.5)
    # 写入第一列
    self.n = len(list)
    for i in range(0, self.n):
        workbook.active.insert_rows(4 + i)  # 在第四行前插入一行，无格式

        for j in range(1, 23):
            self.sheet1.cell(row=4 + i, column=j).border = self.border_set  # 设置插入行的单元格格式
            self.sheet1.cell(row=4 + i, column=j).font = self.font1
            self.sheet1.cell(row=4 + i, column=j).number_format = '0.00'  # 设置插入行的单元格数字格式为保留两位小数
            # 设置单元格自动换行，居中
            self.sheet1.cell(row=4 + i, column=j).alignment = Alignment(horizontal='center', vertical='center',
                                                                        text_rotation=0, wrap_text=True,
                                                                        shrink_to_fit=False, indent=0)

        m = len(self.list[i])  # 通过数据长度修改行高
        if m > 4:
            self.sheet1.row_dimensions[4 + i].height = 30
        if m > 8:
            self.sheet1.row_dimensions[4 + i].height = 45
        self.sheet1.cell(4 + i, 1).value = self.list[i]  # 写入单元格

    workbook.save('test1.xls')

    # 循环输入
    self.ldlen = len(self.land)
    self.llen = len(list)
    self.qlen = len(self.qsdwmc)
    for l1 in range(0, self.llen):  # 确定行数

        for ld1 in range(0, self.ldlen):  # 循环，换行

            if self.list[l1] == self.qsdwmc[0]:  # 根据行标题写书行数据

                for ld1 in range(0, self.ldlen):  # 遍历land

                    if self.land[ld1] == self.dlmc[0]:  # 判断匹配
                        # 其他写入方法
                        # sheet1['%s%s' % (types2[ld1],types3[l1])] = sarea[0]
                        # sheet1.cell(row = l1 + 4,column = types[ld1],value = sarea[0])

                        data = self.sheet1.cell(4 + l1, self.types[ld1]).value  # 用于判断单元格是否为空
                        sum1 = self.sheet1.cell(4 + l1, 22).value  # 用于同名称数据相加

                        if data is None:  # 判断是否为空
                            self.sheet1.cell(4 + l1, self.types[ld1]).value = self.sarea[0]  # 空值直接写入
                            workbook.save('test1.xlsx')

                            # sheet1.column_dimensions[types2[ld1]].width = 8  # 写入后调整列宽
                            workbook.save('test1.xlsx')
                        else:
                            sarea2 = data + self.sarea[0]  # 非空值进行相加后写入
                            self.sheet1.cell(4 + l1, self.types[ld1]).value = sarea2
                            workbook.save('test1.xlsx')

                        if sum1 is None:  # 判断合计列单元格是否为空
                            self.sheet1.cell(4 + l1, 22).value = self.sarea[0]  # 空值直接写入
                            workbook.save('test1.xlsx')
                        #     sheet1.column_dimensions['V'].width = 8   # 设置列宽
                        #     workbook.save('test1.xlsx')
                        else:
                            sum = sum1 + self.sarea[0]  # # 非空值进行相加后写入
                            self.sheet1.cell(4 + l1, 22).value = sum
                            workbook.save('test1.xlsx')
                    else:
                        pass

                self.qsdwmc.pop(0)  # 删除第0个，以保证每次循环取数正确
                self.dlmc.pop(0)
                self.sarea.pop(0)
            elif self.qsdwmc[0] == '':  # 有效循环结束时，碰到空字符时结束全部循环
                return 0
            else:  # 判断不一样，跳过

                break

    workbook.save('test1.xlsx')  # 保存


# 计算合计部分
def summation(self):
    file = 'test1.xlsx'
    workbook = xlrd.open_workbook(file)  # 创建工作空间
    self.sheet1 = workbook.sheet_by_index(0)  # 选取第0个表

    workbook2 = openpyxl.load_workbook(file)  # 创建工作空间
    self.sheet2 = workbook2['Sheet1']  # 选取Sheet1表

    self.types.append(22)  # 在types中添加一列，以获取全部有效数值
    self.types2.append('V')

    self.cols_sum = locals()  # 设置列和动态变量
    self.cols_list = locals()  # 设置列值动态变量
    a = 0
    for i in self.types:
        self.cols_list['cols_list_' + str(i - 1)] = []  # 创建动态变量列表
        self.cols_list['cols_list_' + str(i - 1)] = (self.sheet1.col_values(i - 1))  # 获取i-1列的值
        self.cols_list['cols_list_' + str(i - 1)].pop(0)  # 删除第0个值，为了删除前三个标题
        self.cols_list['cols_list_' + str(i - 1)].pop(0)
        self.cols_list['cols_list_' + str(i - 1)].pop(0)

        # print(cols_list['cols_list_' + str(i - 1)])
        # print(len(cols_list['cols_list_' + str(i - 1)]))
        self.lc = len(self.cols_list['cols_list_' + str(i - 1)])  # 有效数值的行数

        for j in self.cols_list['cols_list_' + str(i - 1)]:  # 循环求和

            data = self.sheet2.cell(self.lc + 3, i).value  # 用于检测单元格是否为空

            if j == '':  # 空值跳过

                pass

            elif data is None:  # 单元格为空值加入数值
                self.sheet2.cell(self.lc + 3, i).value = j

            else:  # 求和
                sum2 = data + j
                self.sheet2.cell(self.lc + 3, i).value = sum2
                # sheet2.column_dimensions[i].width = len(sum2)  # 设置列宽
                # sheet2.column_dimensions[i].auto_size = True
                self.sumlen = len(str(sum2).split('.')[0])  # float无法计算len，先变成str再取整数部分
                self.sheet2.column_dimensions[self.types2[a]].width = self.sumlen + 3.5  # 自适应列宽
                # print(len(str(sum2).split('.')[0]))

                workbook2.save('test2.xlsx')
        a = a + 1
    sum_list = self.sheet2.cell(11, 22).value


def landform_creat(self):
    self.landform_basics()
    self.readexcel()
    self.writeexcel()
    self.summation()
    # if __name__ == '__main__':
    #     readexcel()
    #     writeexcel()
    #     summation()
